package com.bjpowernode.crm.interceptor;

import com.bjpowernode.crm.commons.contans.Contans;
import com.bjpowernode.crm.settings.domain.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录验证拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //根据session判断用户是否登录成功;

        //得到session
        HttpSession session = httpServletRequest.getSession();

        //获取user
        User user = (User) session.getAttribute(Contans.SESSION_USER);
        if(user == null){
            //如果用户没有登录成功,则跳转到登录页面

            //重定向,手动重定向url必须加项目名称

            httpServletResponse.sendRedirect(httpServletRequest.getContextPath());//httpServletRequest.getContextPath() 获取项目url路径
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
